
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace SharpSoft.Data
{
#if NETSTANDARD
    using Microsoft.Data.Sqlite;
    using SqliteFactory = Microsoft.Data.Sqlite.SqliteFactory;
    using CONNECTION = Microsoft.Data.Sqlite.SqliteConnection;
    using CONNECTIONSTRINGBUILDER = Microsoft.Data.Sqlite.SqliteConnectionStringBuilder;
#else

    using System.Data.SQLite;
    using SqliteFactory = System.Data.SQLite.SQLiteFactory; 
    using CONNECTION = System.Data.SQLite.SQLiteConnection;
    using CONNECTIONSTRINGBUILDER = System.Data.SQLite.SQLiteConnectionStringBuilder;
#endif
    using SharpSoft.Data.GSQL;
    using System.ComponentModel;
    using System.IO;

    [DisplayName("Sqlite数据库")]
    public class Sqlite : Database
    {
        public Sqlite(string p_connstr) : base(SqliteFactory.Instance, p_connstr)
        {

        }
        public static Database CreateSchema(string dbFileName)
        {
#if NETSTANDARD
            File.Create(dbFileName).Dispose();
#else
            SQLiteConnection.CreateFile(schemaName);
#endif
            return new Sqlite(CreateConnectionString(dbFileName, ""));
        }

        public override void Dispose()
        {
#if !NETSTANDARD //.NET CORE的SQLite连接程序暂不支持清除连接池
            if (this.ClearPoolWhenDispose)
            { 
                CONNECTION.ClearPool((CONNECTION)this.conn);
            }
#else

#endif
            base.Dispose();
        }


        public static string CreateConnectionString(string filename, string pwd,Dictionary<string,string> otherProps=null)
        {
            StringBuilder sb = new StringBuilder();
            CONNECTIONSTRINGBUILDER.AppendKeyValuePair(sb, "DataSource", filename);
            // CONNECTIONSTRINGBUILDER.AppendKeyValuePair(sb, "Version", "3");
            if (!string.IsNullOrEmpty(pwd))
            {
                CONNECTIONSTRINGBUILDER.AppendKeyValuePair(sb, "Password", pwd);
            }
            if (otherProps!=null)
            {
                foreach (var item in otherProps)
                {
                    CONNECTIONSTRINGBUILDER.AppendKeyValuePair(sb, item.Key, item.Value);
                }
            }
            return sb.ToString();

        }

        public override SQLTextGenerator SQLTextGenerator()
        {
            return new SqliteTextGenerator();
        }

        public override SqlPagination<TModel> ExecutePagination<TModel>(NativeSQLCommandScript select, int onepagerowscount, int curpageindex, object paras = null)
        {//TODO:实现sqlite原生语句的分页查询
            throw new NotImplementedException();
        }
    }
}
